package com.wcs.exam.common.config;

import cn.hutool.core.util.StrUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

/**
 * @author wcs
 */
@Configuration
@EnableAsync
public class ThreadPoolConfig {

    /**
     * 线程池维护线程的最少数量
     */
    private static final int CORE_POOL_SIZE = 20;

    /**
     * 线程池维护线程的最大数量
     */
    private static final int MAX_POOL_SIZE = 100;

    /**
     * 缓存队列
     */
    private static final int QUEUE_CAPACITY = 1000;

    /**
     * 允许的空闲时间（单位：秒）
     */
    private static final int KEEP_ALIVE = 120;

    @Value("${spring.application.name}")
    private String applicationName;

    @Bean(name = "threadPoolTaskExecutor")
    public ThreadPoolTaskExecutor initExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        if (StrUtil.isBlank(applicationName)) {
            executor.setThreadNamePrefix("executor-");
        } else {
            executor.setThreadNamePrefix(applicationName + "-executor-");
        }

        // 使用此策略，如果添加到线程池失败，那么主线程会自己去执行该任务，不会等待线程池中的线程去执行。若不设置，则为默认策略（AbortPolicy）：丢弃任务并抛出RejectedExecutionException异常。
        //executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        executor.setCorePoolSize(CORE_POOL_SIZE);
        executor.setMaxPoolSize(MAX_POOL_SIZE);
        executor.setQueueCapacity(QUEUE_CAPACITY);
        executor.setKeepAliveSeconds(KEEP_ALIVE);
        executor.initialize();
        return executor;
    }
}
